﻿using AuthenticationTest;
using AutoMapper;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MimeKit;
using System.IdentityModel.Tokens.Jwt;
using Newtonsoft.Json;
using WidgetsDesign.API.Dtos;
using WidgetsDesign.API.Helper;
using WidgetsDesign.API.Models;
using WidgetsDesign.API.Services;
using static WidgetsDesign.API.Controllers.UserController;

namespace WidgetsDesign.API.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly IUserRepository _userRepository;
        private readonly IMapper _mapper;
        private readonly JwtHelper _jwtHelper;
        private readonly IWebHostEnvironment _webHostEnvironment;

        public UserController(IUserRepository userRepository, IMapper mapper, JwtHelper jwtHelper,
            IWebHostEnvironment webHostEnvironment)
        {
            _userRepository = userRepository;
            _mapper = mapper;
            _jwtHelper = jwtHelper;
            _webHostEnvironment = webHostEnvironment;
        }

        /// <summary>
        /// 发送手机验证码 暂时不用
        /// </summary>
        /// <param name="p">加密后手机号字符串</param>
        /// <param name="t">类型  password/register</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> SendSmsCode([FromQuery] string p, string t)
        {
            var PhoneNumber = AESHelper.EncryptUtil.DecryptAES(p, "!Widgetsdesign@7", "!Widgetsdesign@&");

            if (PhoneNumber != "" && t == "register")
            {
                var UserInfo = await _userRepository.GetUserInfoByPhoneNumber(PhoneNumber);
                if (UserInfo == null)
                {
                    var code = _userRepository.GetRandomVerificationCode();
                    //var today = await _userRepository.QueryTodayVerificationCodeCount(PhoneNumber, t);
                    var today = 3;
                    if (today < 3)
                    {
                        var smsResult = SmsHelper.SendPhone(code: code, phoneNumber: PhoneNumber);
                        if (smsResult == "OK")
                        {
                            //var NewList = new VerificationCodeModel
                            //{
                            //    VerificationCode = int.Parse(code),
                            //    Type = "register",
                            //    PhoneNumber = PhoneNumber,
                            //    CreateTime = DateTime.Now,
                            //};
                            //_userRepository.CreateVerificationCode(NewList);
                            //await _userRepository.SaveAsync();
                            return Ok(new { code = 200, message = "发送成功" });
                        }
                    }

                    return Ok(new { code = 0, message = "今日发送短信过多，请联系管理员或明日再试！" });
                }

                return Ok(new { code = 0, message = "该手机号码已注册，请直接登录" });
            }

            return BadRequest("非法调用");
        }

        /// <summary>
        /// 发送邮箱验证码
        /// </summary>
        /// <param name="e">邮箱地址</param>
        /// <param name="t">验证码类型</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> SendEmailCode([FromQuery] string e, string t)
        {
            //验证邮箱合法性
            if (!RegexHelper.IsEmail(e))
            {
                return Ok(new { code = 0, message = "邮箱格式不正确" });
            }

            //验证参数’
            if (t == "ResetPassWord" && t == "Register")
            {
                return Ok(new { code = 0, message = "参数错误" });
            }

            //验证邮箱是否已注册
            var userInfo = await _userRepository.GetUserInfoByEmail(e);
            if (t == "ResetPassWord" && userInfo == null)
            {
                return Ok(new { code = 0, message = "该邮箱未注册，请直接注册使用" });
            }

            if (t == "Register" && userInfo != null)
            {
                return Ok(new { code = 0, message = "该邮箱已注册，请直接登录" });
            }

            //生成一个6位数的验证码
            var code = _userRepository.GetRandomVerificationCode(6);
            var result = EmailHelper.SendEmail("验证码", e, e, code);
            if (!result)
            {
                return Ok(new { code = 0, message = "发送失败，请稍后重试，或联系管理员！" });
            }

            var list = new VerificationCodeModel
            {
                VerificationCode = int.Parse(code),
                Type = t,
                UserEmail = e,
                CreateTime = DateTime.Now,
            };
            await _userRepository.CreateVerificationCode(list);
            await _userRepository.SaveAsync();
            return Ok(new { code = 200, message = "发送成功，验证码十分钟之内有效！" });
        }

        public class RegisterModel
        {
            public string PhoneNumber { get; set; }
            public int Code { get; set; }
            public string PassWord { get; set; }
        }

        /// <summary>
        /// 短信注册
        /// </summary>
        /// <param name="registerModel"></param>
        /// <returns></returns>
        [HttpPost(Name = "Register")]
        public async Task<IActionResult> RegisterSms([FromBody] RegisterModel registerModel)
        {
            var result = await _userRepository.ValidateVerificationCode(registerModel.PhoneNumber, registerModel.Code);
            switch (result)
            {
                case 1:
                    return Ok(new { code = 0, message = "验证码输入错误!" });
                case 2:
                    return Ok(new { code = 200, message = "验证码超时!" });
                default:
                    var userInfo = await _userRepository.GetUserInfoByPhoneNumber(registerModel.PhoneNumber);
                    if (userInfo != null)
                    {
                        return Ok(new { code = 0, message = "该账户已存在" });
                    }

                    //1. 保存到userInfo 
                    var newUser = new UserInfo
                    {
                        UserName = "手机用户" + registerModel.PhoneNumber,
                        Uuid = Guid.NewGuid(),
                        PhoneNumber = registerModel.PhoneNumber,
                        PassWord = registerModel.PassWord,
                        Wallet = 0,
                        CreateTime = DateTime.Now,
                    };
                    _userRepository.CreateUserInfo(newUser);
                    await _userRepository.SaveAsync();
                    //2. 返回
                    return Ok(new { code = 200, message = "成功" });
            }
        }

        public class RegisterEmailModel
        {
            public string Email { get; set; }
            public string PassWord { get; set; }
            public string Code { get; set; }
        }

        /// <summary>
        /// 邮箱注册
        /// </summary>
        /// <param name="registerModel"></param>
        /// <returns></returns>
        [HttpPost(Name = "RegisterEmail")]
        public async Task<IActionResult> RegisterEmail([FromBody] RegisterEmailModel registerModel)
        {
            var userInfo = await _userRepository.GetUserInfoByEmail(registerModel.Email);

            if (userInfo != null)
            {
                return Ok(new { code = 0, message = "该用户已注册，请直接登录" });
            }

            var result =
                await _userRepository.ValidateVerificationCode(registerModel.Email, int.Parse(registerModel.Code));
            switch (result)
            {
                case 1:
                    return Ok(new { code = 0, message = "验证码输入错误!" });
                case 2:
                    return Ok(new { code = 200, message = "验证码超时!" });
                default:
                    //1. 保存到userInfo 
                    var newUser = new UserInfo
                    {
                        UserName = "邮箱用户" + registerModel.Email,
                        Uuid = Guid.NewGuid(),
                        UserEmail = registerModel.Email,
                        PassWord = registerModel.PassWord,
                        Wallet = 0,
                        CreateTime = DateTime.Now,
                    };
                    _userRepository.CreateUserInfo(newUser);
                    await _userRepository.SaveAsync();
                    //2. 返回
                    return Ok(new { code = 200, message = "成功" });
            }
        }


        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="loginModel"></param>
        /// <returns></returns>
        public class LoginModel
        {
            public string Email { get; set; }
            public string PassWord { get; set; }
        }

        [HttpPost]
        public async Task<IActionResult> Login([FromBody] LoginModel loginModel)
        {
            var userInfo = await _userRepository.GetUserInfoByEmail(loginModel.Email);
            if (userInfo == null)
            {
                return Ok(new { code = 0, message = "该邮箱未注册！" });
            }

            if (userInfo.PassWord == loginModel.PassWord)
            {
                return Ok(new { code = 0, message = "密码错误！" });
            }

            var jwt = _jwtHelper.CreateToken();
            var user = _mapper.Map<UserInfoDto>(userInfo);
            var obj = new { jwt = jwt, userInfo = user };
            string json = JsonConvert.SerializeObject(obj);
            var encryptionString =
                AESHelper.EncryptUtil.EncryptAES(json, "!Widgetsdesign@7", "!Widgetsdesign@&");
            return Ok(new { code = 200, data = encryptionString, message = "登录成功！" });
        }


        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="resetPassword"></param>
        /// <returns></returns>
        public class ResetPasswordModel
        {
            public string Email { get; set; }
            public string PassWord { get; set; }
            public string Code { get; set; }
        }

        [HttpPost]
        public async Task<IActionResult> ResetPassword([FromBody] ResetPasswordModel resetPassword)
        {
            var userInfo = await _userRepository.GetUserInfoByEmail(resetPassword.Email);
            if (userInfo == null)
            {
                return Ok(new { code = 0, message = "该邮箱未注册！" });
            }

            var result =
                await _userRepository.ValidateVerificationCode(resetPassword.Email, int.Parse(resetPassword.Code));
            switch (result)
            {
                case 1:
                    return Ok(new { code = 0, message = "验证码输入错误!" });
                case 2:
                    return Ok(new { code = 200, message = "验证码超时!" });
                default:
                    await _userRepository.ResetPassword(resetPassword.Email, resetPassword.PassWord);
                    await _userRepository.SaveAsync();
                    return Ok(new { code = 200, message = "重置成功，请登录！" });
            }
        }

        /// <summary>
        /// 修改用户名
        /// </summary>
        /// <param name="updateUserName"></param>
        /// <returns></returns>
        public class UpdateUserNameModel
        {
            public Guid Uuid { get; set; }
            public string UserName { get; set; }
        }

        [HttpPost]
        public async Task<IActionResult> UpdateUserName([FromBody] UpdateUserNameModel updateUserName)
        {
            var userInfo = await _userRepository.GetUserInfoByUuid(updateUserName.Uuid);
            if (userInfo == null)
            {
                return Ok(new { code = 0, message = "未找到该用户！" });
            }

            await _userRepository.UpdateUserName(updateUserName.Uuid, updateUserName.UserName);
            await _userRepository.SaveAsync();
            return Ok(new { code = 200, message = "修改成功！" });
        }

        [HttpGet("{uuid}")]
        public async Task<IActionResult> GetUserInfo([FromRoute] Guid uuid)
        {
            var userInfo = await _userRepository.GetUserInfoByUuid(uuid);
            if (userInfo == null)
            {
                return Ok(new { code = 0, message = "未找到该用户！" });
            }
            var jwt = _jwtHelper.CreateToken();
            var user = _mapper.Map<UserInfoDto>(userInfo);
            var obj = new { jwt = jwt, userInfo = user };
            string json = JsonConvert.SerializeObject(obj);
            var encryptionString =
                AESHelper.EncryptUtil.EncryptAES(json, "!Widgetsdesign@7", "!Widgetsdesign@&");
            return Ok(new { code = 200, data = encryptionString, message = "获取成功！" });
        }
    }
}